package com.xcl.seckill.Controller;

import com.xcl.seckill.dao.UserDOMapper;
import com.xcl.seckill.error.BusinessException;
import com.xcl.seckill.error.EmBusinessError;
import com.xcl.seckill.model.UserDO;
import com.xcl.seckill.response.CommonReturnType;
import com.xcl.seckill.service.UserService;
import com.xcl.seckill.service.domain.UserModel;
import com.xcl.seckill.viewObject.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.reflect.generics.tree.ByteSignature;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Random;

@Controller
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class UserController extends BaseController {
    @Autowired
    UserService userService;
    @Autowired
    HttpServletRequest request;
    @ResponseBody
    @RequestMapping(value = "/login",method = {RequestMethod.POST},consumes ={ CONTENT_TYPE_FORMED})
    public CommonReturnType login(@RequestParam(name = "telphone") String telphone,
                                  @RequestParam(name = "password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        if(StringUtils.isEmpty(telphone)||StringUtils.isEmpty(password)){
            throw  new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        UserModel userModel=  userService.validataLogin(telphone,this.EncodeByMD5(password));
        this.request.getSession().setAttribute("IS_LOGIN",true);
        this.request.getSession().setAttribute("LOGIN_USER",userModel);
        return CommonReturnType.create(null);
    }
    @ResponseBody
    @RequestMapping(value = "/register",method = {RequestMethod.POST},consumes ={ CONTENT_TYPE_FORMED})
    public CommonReturnType register(@RequestParam(name = "telphone")String telphone,
                                     @RequestParam(name = "otpCode" )String otpCode,
                                     @RequestParam(name = "name" )String name,
                                     @RequestParam(name = "gender" )byte gender ,
                                     @RequestParam(name = "age" )Integer age,
                                     @RequestParam(name = "password" )String password
                                     ) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        String isSessionOtpCode =(String)this.request.getSession().getAttribute(telphone);
        if(!com.alibaba.druid.util.StringUtils.equals(otpCode,isSessionOtpCode)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"短信验证错误");
        }
         UserModel userModel=new UserModel();
        userModel.setAge(age);
      userModel.setGender(gender);
        userModel.setName(name);
        userModel.setTelphone(telphone);
        userModel.setRegisterMode("byphone");
        userModel.setEncrptPassword(this.EncodeByMD5(password));
        userService.register(userModel);
        return CommonReturnType.create(null);
    }
    public String EncodeByMD5(String str)throws NoSuchAlgorithmException,UnsupportedEncodingException{
        MessageDigest md5=MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder=new BASE64Encoder();
        String newstr=base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
    @ResponseBody
    @RequestMapping(value = "/getotp",method = {RequestMethod.POST},consumes ={ CONTENT_TYPE_FORMED})
    public  CommonReturnType getOtp(@RequestParam(name = "telphone")String telphone){
        Random random = new Random();
        int randomInt=random.nextInt(99999);
        randomInt+=10000;
        String otpCode=String.valueOf(randomInt);
        request.getSession().setAttribute(telphone,otpCode);
        System.out.println("telphone"+telphone+"    &&otpCode"+otpCode);
        return CommonReturnType.create(null);
    }

    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType get(@RequestParam(name = "id") Integer id) throws BusinessException {
             UserModel userModel=userService.getUserById(id);
             if (userModel==null){
                 throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
             }
             UserVo userVo=coverFromDataObject(userModel);
             return CommonReturnType.create(userVo);
    }


    UserVo  coverFromDataObject(UserModel userModel) {
     if(userModel==null) {
         return  null;
         }
     UserVo uservo=new UserVo();
        BeanUtils.copyProperties(userModel,uservo);
        return uservo;
    }



}
